package com.qf.login.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.login.entity.User;
import com.qf.login.mapper.UserDao;
import com.qf.login.service.UserService;
import com.qf.login.vo.RegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void regist(RegistVo registVo) {

        //1. 重名判断
        String username = registVo.getUsername();
        User dbuser = userDao.selectOne(new QueryWrapper<User>().eq("username", username));
        if (dbuser!=null){
            throw new RuntimeException("用户名重复了");
        }
        //2. 密码md5运算
        String pwd = registVo.getPwd();
        // 获取盐
        String salt = UUID.randomUUID().toString().replaceAll("-","").substring(10, 18);
        String md5Pwd = DigestUtil.md5Hex(pwd + salt);
        //3. 落库
        User newUser = new User(null, username, md5Pwd, "", new Date(), salt);
        userDao.insert(newUser);

    }

    @Override
    public User login(String username, String password) {

        //1. 根据username查询数据库中的对应的user对象
        User dbuser = userDao.selectOne(new QueryWrapper<User>().eq("username", username));

        if (dbuser==null){
            throw new RuntimeException("用户名不存在");
        }
        //2. 比对密码
        String pwd = DigestUtil.md5Hex(password + dbuser.getSalt());
        if (!pwd.equals(dbuser.getPassword())){
            throw new RuntimeException("密码错误哦");
        }
        log.info("登录成功，username={}",username);

        //3. 把敏感字段去掉
        dbuser.setPassword("***");
        dbuser.setSalt("***");

        return dbuser;
    }

    @Override
    public void updateAvatar(String avatarName, Integer userid) {

        //1. 根据id查询用户信息
        User dbuser = userDao.selectById(userid);

        if (dbuser==null){
            throw new RuntimeException("用户id错误");
        }

        //2. 更新头像信息,只更新用户头像字段，其他字段不更新
        User user = new User();
        user.setUserId(userid);
        user.setUserImg(avatarName);
        userDao.updateById(user);

    }
}
